package cn.edu.xust.AuthJwt;


import cn.edu.xust.configuration.exception.Default200Exception;
import cn.edu.xust.entity.SysUserEntity;
import cn.edu.xust.service.SysRoleprivilegeService;
import cn.edu.xust.service.SysUserService;
import cn.edu.xust.util.JWTUtil;
import cn.edu.xust.util.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@Slf4j
@Component
public class MyRealm extends AuthorizingRealm {


    @Resource
    private SysRoleprivilegeService sysRoleprivilegeService;

    @Resource
    private SysUserService sysUserService;

    @Autowired
    private RedisUtil redisUtil;

    /**
     * 根据token判断此Authenticator是否使用该realm
     *
     * @param token
     * @return
     */
    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof JWTToken;
    }

    /**
     * 只有当需要检测用户权限的时候才会调用此方法，
     * 例如@RequiresRoles,@RequiresPermissions之类的
     *
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {


        log.info("~~~~~~~~~~~~~授权~~~~~~~~~~~~~~");
        String token = principalCollection.toString();
        //有时候有barear头 早些不需要 所以统一replace
        String rjwt = token.replace("Bearer ", "");

        //拿到canme
        String username = JWTUtil.getUsername(rjwt);
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();

        //redis会缓存授权后的信息
        String key = "roleinfo:" + username;
        Object o = redisUtil.get(key);
        if (o != null) {
            return (AuthorizationInfo) o;
        }

        //没有缓存就取查  查询某个用户的所有权限
        List<Integer> prevs = new ArrayList<>();
        try {
            prevs = sysRoleprivilegeService.getPrevByUsername(username);
        } catch (Default200Exception e) {
            e.printStackTrace();
        }
        for (Integer prev : prevs) {
            info.addStringPermission(String.valueOf(prev));
        }
        redisUtil.set(key, info, 6 * 60 * 60);
        return info;
    }

    /**
     * 默认使用此方法进行用户名正确与否验证，错误抛出异常即可，
     * 在需要用户认证和鉴权的时候才会调用
     *
     * @param
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        log.info("~~~~~~~~~~~~认证~~~~~~~~~~~~");

        Object credentials = token.getCredentials();
        log.info("token=>" + credentials);
        if (StringUtils.isEmpty(credentials)) {
            throw new AuthenticationException("token为空,请登录之后再操作");
        }
        String jwt = (String) credentials;
        String rjwt = jwt.replace("Bearer ", "");
        String username = null;
        //decode时候出错，可能是token的长度和规定好的不一样了
        try {
            username = JWTUtil.getUsername(rjwt);
        } catch (Exception e) {
            throw new AuthenticationException("token非法，不是规范的token，可能被篡改了，或者过期了");
        }
        if (!JWTUtil.verify(rjwt) || username == null) {
            throw new AuthenticationException("token认证失效，token错误或者过期，重新登陆");
        }
        SysUserEntity user = sysUserService.getByName(username);
        if (user == null) {
            throw new AuthenticationException("该用户不存在");
        }
        log.info("token验证成功=>" + token);
        return new SimpleAuthenticationInfo(jwt, jwt, "MyRealm");
    }
}
